import store from '../../store'
let that=null
//点击查了原图
async function getOriginal(list) {
	for (let item of list) {
		if (item.isSeeBig && item.isSeeBig == true) {
			return
		}
		let fileUrl = await getOriginalPictureURLByFileId(item)
		if (fileUrl) {
			item.fileUrl = fileUrl
			// item.isSeeBig=true
		}
	}
}

function getOriginalPictureURLByFileId(item) {
	return new Promise((reslove, reject) => {
		let req = {
			fileId: item.fileId, //图片id
		}
		uni.$u.get(store.getters['api'].GLOBAL_file_fileInfo_getOriginalPictureURLByFileId, req).then(res => {
			if (res.code == 200) {
				reslove(res.data)
			}
		})
	})
}
/**
 * @param {arr} list 浏览图片的列表数组
 * @param {object} row  数组中当前图片对象的信息
 * @param {number} index  当前图片对象的下表
 * @param {string} type  当前点击的是否是眼睛图片（original代表原图，默认不传）
 * @param {object} _this 当前vue实例对象
 **/
// 点击查看图片预览
async function previewImage(list, row, index, type,_this) {
	//console.log(row);
	//如果开启了只有点击才加载量子解密
	//enType  加密类型  0：无加密  1：AES加密  2：RSA加密  3：国盾量子加密  4：国科量子加密  
	//enSave  0明文存储  1密文存储 (明文存储需要请求另外接口 ，服务端进行加密在传给前端 )
	if ((row.enType == 3 || row.enType == 4) && row.QSS !== false) {
		const SystemInfo = uni.getSystemInfoSync();
		if (SystemInfo.platform != 'ios') {
			if((row.enType == 3 || row.enType == 4)&&row.enSave==0){
				let decryptData= await quantumCryptographyPretreatment(row,_this)
				if(decryptData){
					row.QssfileUrl=decryptData.fileUrl
					row.enSave=decryptData.enSave
					await previewImage(list, row, index, type,_this)
				}
				return
			}
			if (row.enType == 3) {
				if(getApp().globalData.GD_QSS.enable==true){
					qssAnimateGif(true,_this)
					//国盾解密
					isGDQss(row, index,_this)
				}else{
					// showModal('提醒','检测到您未启用国盾量子解密功能，是否前去开启？','取消','立即设置',1)
					showModal('解密失败','未检测到硬件设备','取消','确定',3)
				}
			} else if (row.enType == 4) {
				if(getApp().globalData.GK_QSS_ONOFF.enable==true){
					qssAnimateGif(true,_this)
					// 国科量子解密
					isgkQSS(row, index,_this)
				}else{
					// showModal('提醒','检测到您未启用国科量子解密功能，是否前去开启？','取消','立即设置',2)
					showModal('解密失败','未检测到硬件设备','取消','确定',3)
				}
				
			} else {
				uni.showToast({
					title: '无法获取加密类型enType',
					icon: 'none'
				});
			}
		}
	} else {
		if (row.QSS == false) { //如果是量子加密的图片则只能一张一张看
			uni.$lizhao.download.qssSave(row.fileUrl)
		} else if (row.fileId) {
			if (type == 'original') {
				uni.$lizhao.debounce(function() {
					uni.showLoading({
						title:row.correctFile?'修正图加载中..':'原图加载中..',
						mask: false
					});
					setTimeout(async () => {
						uni.hideLoading()
						let originalList = JSON.parse(JSON.stringify(list))
						//解决1.0查看原图兼容问题，2.0后此代码可以删除
						await getOriginal(originalList);
						lzpreviewImage(row, index, originalList, _this)
					}, 800)
				})
				return
			}
			lzpreviewImage(row, index, list, _this)
		}
	}
}
//明文存储，服务端加密
function quantumCryptographyPretreatment(row){
	//console.log('明文存储，服务端加密');
	return new Promise((reslove, reject) => {
		let req = {
			fileId: row.fileId,
		}
		uni.$u.get(store.getters['api'].GLOBAL_file_fileInfo_quantumCryptographyPretreatment, req).then(res => {
			//console.log(res.code);
			if (res.code == 200) {
				reslove(res.data)
			}
		}).catch(err=>{
			//console.log('请求失败',err);
		})
	})
}

function lzpreviewImage(row, index, list, _this) {
	// 预览图片
	uni.previewImage({
		urls: list.map(item => item.fileUrl + `?Authorization=${_this.userInfo.token}&us=app`),
		current: index||row.fileUrl,
		longPressActions: {
			itemList: ['保存图片'],
			success: function(data) {
				uni.$lizhao.download.save(row, 'fileUrl', _this.userInfo.token)
			},
			fail: function(err) {
				//console.log(err.errMsg);
			}
		}
	});
}
//是否进行国盾量子解密
async function isGDQss(data, index,_this) {
	//判断链接后面是否有Authorization
	if(data.QssfileUrl.indexOf('Authorization')==-1){
		data.QssfileUrl=data.QssfileUrl+'?Authorization='+_this.userInfo.token+'&us=app'
	}
	let base64Data = await uni.$lizhao.gdQSS.decrypt(data.secretKey, data.QssfileUrl)
	data.QSS = false
	if (base64Data.code == 0) {
		data.fileUrl = base64Data.data
	} else {
		uni.showToast({
			title: base64Data.data.msg || '量子解密失败',
			icon: "none"
		});
		delete data.QSS
		qssAnimateGif(false,_this)
		return
	}
	setTimeout(() => {
		qssAnimateGif(false,_this)
		isNowSee(data, getApp().globalData.GD_QSS)
	}, 800)
}
//是否进行国科量子解密
async function isgkQSS(data, index, _this) {
	//console.log(data.QssfileUrl, data.secretKey);
	let base64 = await uni.$lizhao.QSS.SM4DecryptBigData(data.QssfileUrl, data.secretKey)
	if (base64 == 'data:image/jpg;base64,') {
		uni.showToast({
			title: '量子解密失败',
			icon: "none"
		});
	} else {
		data.fileUrl = base64
	}
	data.QSS = false
	setTimeout(() => {
		qssAnimateGif(false,_this)
		isNowSee(data, getApp().globalData.GK_QSS_ONOFF)
	}, 800)
}
//解密成功后是否立即查看
function isNowSee(data, qss) {
	if (qss.clickDecrypt && qss.nowSee) {
		previewImage([], data)
	}
}
//是否显示动画 onoff true开启
function qssAnimateGif(onoff,_this){
	if(onoff){
		try{
			_this.$refs.qssAnimateGif.open()
		}catch(e){
			_this.qssAnimateGif=true
		}
	}else{
		try{
			_this.$refs.qssAnimateGif.close()
		}catch(e){
			_this.qssAnimateGif=false
		}
	}
	
}
function showModal(title,content,cancelText,confirmText,type){
	uni.showModal({
		title,
		content,
		cancelText,
		confirmText,
		success: res => {
			if(res.confirm){
				if(type==1){
					uni.navigateTo({url: '/pages/template/gdQss/gdQss'});
				}else if(type==2){
					uni.navigateTo({url: '/pages/template/gkQss/gkQss'});
				}else if(type==3){
					//console.log('未检测到硬件设备');
				}
			}
		},
		fail: () => {},
		complete: () => {}
	});
}

export default {
	getOriginal,
	previewImage
}
